import logging
from random import randint

from django import http
from django.views import View
from django_redis import get_redis_connection

from apps.verifications.constant import SMS_CODE_EXPIRE_TIME
from libs.captcha.captcha import captcha
from utils.response_code import RETCODE

logger = logging.getLogger('django')
class ImageCodeView(View):
    def get (self,request,uuid):
        text,image=captcha.generate_captcha()
        #保存ｔｅｘｔ到ｒｅｄｉｃ中
        redis_conn=get_redis_connection("code")
        redis_conn.setex('img_%s'%uuid,120,text)
        return http.HttpResponse(image,content_type='image/jpeg')


class SMSCodeView(View):
    def get (self, request, mobile, ):
        params=request.GET
        uuid=params.get('image_code_id')
        text_client=params.get('image_code')
        try:
            redis_conn=get_redis_connection('code')
            text_server=redis_conn.get('img_%s'%uuid)
            if text_server is None:
                return http.HttpResponseBadRequest('图片验证码已经过期')
            if text_server.decode().lower() !=text_client.lower():
                return http.HttpResponseBadRequest('图片验证码不一致')
            redis_conn.delete('img_%s'%uuid)
        except Exception as e:

            logger.error(e)
            return  http.HttpResponseBadRequest('数据库链接问题')
        send_flag=redis_conn.get("send_flag_%s"%mobile)
        if send_flag is not None:
            return http.HttpResponseBadRequest("操作太频繁了")
        # sms_code=randint(0,99999)
        sms_code='%06d'%randint(0,99999)
        logger.info(sms_code)

        # redis_conn.setex('sms_%s'%mobile,SMS_CODE_EXPIRE_TIME ,sms_code)
        # redis_conn.setex('send_flag_%s'%mobile,60,1)
        # 管提升性能
        pl=redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        # 改为 celery
        from celery_tasks.sms.tasks import send_sms_code
        # delay 的参数 同 任务的参数
        send_sms_code.delay(mobile, sms_code)

        # 6.返回相应
        return http.JsonResponse({'code': RETCODE.OK})









